package com.myownthemepark.s3vn;

public class PostCommitHook {
	public static void main(String[] args){
		String svnZooBucket = null;
		String svnZooPrefix = null;
		String svnZooZKAddr = null;
		String svnZooZKPrefix = null;
		String repoPath = null;
		S3vn s3vn = null;
		long currentLocal;
		int currentRev, currentZoo, ret;
		boolean failure = false;
		if (args.length < 2){
			System.out.println("Usage: java PostCommitHook <repos_path> <rev>");
			return;
		}
		try{
			repoPath = args[0];
			currentRev = Integer.parseInt(args[1]);
			
			svnZooBucket = System.getenv("SVNZOO_BUCKET");
			svnZooPrefix = System.getenv("SVNZOO_PREFIX");
			svnZooZKAddr = System.getenv("SVNZOO_ZKADDR");
			svnZooZKPrefix = System.getenv("SVNZOO_ZKPREFIX");
			s3vn = new S3vn(repoPath, svnZooBucket, svnZooPrefix, svnZooZKAddr, svnZooZKPrefix);
			s3vn.setProgName("post");
			
			s3vn.createZKSession();
			currentLocal = s3vn.getCurrent();
			if (!s3vn.checkLock()){
				System.err.println("Trying to re-acquire the lock, which was somehow lost");
				s3vn.acquireLock();
				currentZoo = s3vn.fetchCurrent();
				if (currentZoo != (currentLocal - 1))
					throw new Exception("Someone committed a newer revision during the time we lost the lock!");
			}
			s3vn.storeRev(currentLocal);
			s3vn.storeCurrent(currentLocal);
			s3vn.deleteZKSession();
			ret = 0;
		}catch (Exception e){
			System.err.println(String.format("[Error]:\n%s\n\n[Stack trace]:", e.toString()));
			StackTraceElement[] ste = e.getStackTrace();
			int i;
			for (i = 0; i < ste.length; i++){
				System.out.println(ste[i]);
			}
			failure = true;
			ret = 1;
		}finally{
			try{
				if (!failure){
					s3vn.releaseLock();
					s3vn.endZKSession();
				}
			}catch (Exception e){
				System.err.println(String.format("[Error]:\n%s\n\n[Stack trace]:", e.toString()));
				StackTraceElement[] ste = e.getStackTrace();
				int i;
				for (i = 0; i < ste.length; i++){
					System.out.println(ste[i]);
				}
			}
		}
		System.exit(ret);
	}
}